﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace WinBolo_Tracker
{
    public class NetworkException : Exception
    {
        public NetworkException(string msg)
            : base(msg)
        {
        }

        public NetworkException(string msg, Exception e)
            : base(msg, e)
        {
        }
    }

    public class Network
    {
        public static string SocketSendReceive(string server, int port)
        {
            string request = "";
            string response = "";
            Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
            Byte[] bytesReceived = new Byte[256];

            try
            {
                Socket s = ConnectSocket(server, port);

                if (s == null)
                    throw new NetworkException("Connect to socket returned null");

                s.Send(bytesSent, bytesSent.Length, 0);

                int bytes = 0;

                do
                {
                    bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
                    response = response + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
                }
                while (bytes > 0);
            }
            catch (Exception e)
            {
                // Log error
                Logger.Log(e.Message);

                response = "";
            }

            return response;
        }

        private static Socket ConnectSocket(string server, int port)
        {
            Socket s = null;
            IPHostEntry hostEntry = null;

            hostEntry = Dns.GetHostEntry(server);

            foreach (IPAddress address in hostEntry.AddressList)
            {
                IPEndPoint ipe = new IPEndPoint(address, port);
                Socket tempSocket =
                    new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                tempSocket.Connect(ipe);

                if (tempSocket.Connected)
                {
                    s = tempSocket;
                    break;
                }
                else
                {
                    continue;
                }
            }

            return s;
        }
    }
}
